import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

const state = {
  list: [],
  btnType: 'all' // 按钮类型
}

const mutations = {
  setList(state, list) {
    state.list = list
  },
  // 添加事项
  addItem(state, item) {
    state.list.push(item)
  },
  // 删除
  deleteItem(state, id) {
    const i = state.list.findIndex(item => item.id === id)
    if (i !== -1) {
      state.list.splice(i, 1)
    }
  },
  // 清除已完成
  clearDone(state) {
    state.list = state.list.filter(item => !item.checked)
  },
  // 更新按钮类型
  updateBtnType(state, type) {
    state.btnType = type
  }
}

const actions = {
  // 异步加载数据
  asyncGetList() {
    axios.get('/list.json').then(res => {
      this.commit('setList', res.data)
    })
  }
}

const getters = {
  // 统计未完成条数
  unDoneLength(state) {
    return state.list.filter(item => !item.checked).length
  },
  // 筛选 list
  filterList(state) {
    if (state.btnType === 'all') return state.list
    else if (state.btnType === 'undone') return state.list.filter(item => !item.checked)
    else if (state.btnType === 'done') return state.list.filter(item => item.checked)
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  modules: {}
})
